package com.springboot.framework.controller;

import com.springboot.framework.controller.request.OrderStatusUpdateRequestBean;
import com.springboot.framework.controller.request.OrderCreateBean;
import com.springboot.framework.enums.Errors;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.BuyerModel;
import com.springboot.framework.model.OrderDetailModel;
import com.springboot.framework.model.OrderModel;
import com.springboot.framework.model.UserModel;
import com.springboot.framework.service.BuyerService;
import com.springboot.framework.service.OrderService;
import com.springboot.framework.utils.ResponseVoUtil;
import com.springboot.framework.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author SWF
 * @Date 2019/6/10 14:44
 **/
@Api(description = "【买家】订单")
@RestController
@RequestMapping("/buyer/order")
public class BuyerOrderController extends BaseController {
    @Resource
    private OrderService orderService;

    @Resource
    private BuyerService buyerService;

//    @ApiOperation(value = "创建订单",notes = "创建订单")
//    @PostMapping("/create1")
//    @ResponseBody
//    public ResponseVO<OrderModel> create1(@RequestBody @Valid OrderCreateBean bean , BindingResult bindingResult, HttpServletRequest request){
//        UserModel userModel = super.getSessionUser(request);
//        if(bindingResult.hasErrors()){
//            throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
//        }
//        OrderModel orderModel = convertOrderModelFromOrderCreateBean(bean);
//        orderModel.setUserId(userModel.getId());
//        orderService.create(orderModel);
//        return ResponseVoUtil.success(orderModel);
//    }

    @ApiOperation(value = "创建订单 临时",notes = "创建订单 临时，传入openid，根据openid查找用户")
    @PostMapping("/create")
    public ResponseVO<OrderModel> create(@RequestBody @Valid OrderCreateBean bean , BindingResult bindingResult, HttpServletRequest request){
        // 基础校验
        if(bindingResult.hasErrors()){
            throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
        }
        // 获取用户信息
        BuyerModel buyerModel = buyerService.getByOpenId(bean.getUserWechatOpenid());
        if(buyerModel == null){
            throw new BusinessException(Errors.USER_NOT_FIND);
        }
        OrderModel orderModel = convertOrderModelFromOrderCreateBean(bean);
        orderModel.setUserId(buyerModel.getId());
        orderService.create(orderModel);
        return ResponseVoUtil.success(orderModel);
    }

    @ApiOperation(value = "查看订单列表",notes = "查看订单")
    @GetMapping("/list")
    public ResponseVO<List<OrderModel>> list(@RequestParam String openId, HttpServletRequest request){
        //TODO 临时设置为前端传入用户凭证
        //UserModel userModel = super.getSessionUser(request);
        UserModel userModel = buyerService.getByOpenId(openId);
        if(userModel == null){
            throw new BusinessException(Errors.USER_NOT_FIND);
        }
        List<OrderModel> orderModels = orderService.listByUserId(userModel.getId());
        return ResponseVoUtil.success(orderModels);
    }

    @ApiOperation(value = "查看订单列表根据状态",notes = "查看订单根据状态")
    @GetMapping("/listByStatus")
    public ResponseVO<List<OrderModel>> listByStatus(@RequestParam String openId, @RequestParam Byte status, HttpServletRequest request){
        //UserModel userModel = super.getSessionUser(request);
        UserModel userModel = buyerService.getByOpenId(openId);
        if(userModel == null){
            throw new BusinessException(Errors.USER_NOT_FIND);
        }
        List<OrderModel> orderModels = new ArrayList<OrderModel>();
        if(status == -1){
            orderModels = orderService.listByUserId(userModel.getId());
        }else{
            orderModels = orderService.listByUserIdAndStatus(userModel.getId(),status);
        }
        return ResponseVoUtil.success(orderModels);
    }

    @ApiOperation(value = "查看订单详情",notes = "查看订单详情")
    @GetMapping("/get")
    public ResponseVO<OrderModel> get(String orderId, HttpServletRequest request){
        OrderModel orderModel = checkOrderOwner(orderId,request);
        return ResponseVoUtil.success(orderModel);
    }

    @ApiOperation(value = "取消订单",notes = "取消订单")
    @PostMapping("/cancel")
    public ResponseVO<OrderModel> cancel(@RequestBody OrderStatusUpdateRequestBean bean, HttpServletRequest request){
       // OrderModel orderModel = checkOrderOwner(orderId,request);
        OrderModel orderModel = checkOrderOwner(bean.getOrderId(),bean.getOpenId());
        orderModel = orderService.cancel(orderModel);
        return ResponseVoUtil.success(orderModel);
    }

    @ApiOperation(value = "完结订单",notes = "完结订单")
    @PostMapping("/finish")
    public ResponseVO<OrderModel> finish(@RequestBody OrderStatusUpdateRequestBean bean, HttpServletRequest request){
        OrderModel orderModel = checkOrderOwner(bean.getOrderId(),bean.getOpenId());
        orderModel = orderService.finish(orderModel);
        return ResponseVoUtil.success(orderModel);
    }

    @ApiOperation(value = "支付订单",notes = "支付订单")
    @PostMapping("/paid")
    public ResponseVO<OrderModel> paid(@RequestBody OrderStatusUpdateRequestBean bean, HttpServletRequest request){
        OrderModel orderModel = checkOrderOwner(bean.getOrderId(),bean.getOpenId());
        orderModel = orderService.paid(orderModel);
        return ResponseVoUtil.success(orderModel);
    }

    private OrderModel checkOrderOwner(String orderId, HttpServletRequest request){
        UserModel userModel = super.getSessionUser(request);
        OrderModel orderModel = orderService.get(orderId);
        if(!orderModel.getUserId().equals(userModel.getId())){
            // 该订单不属于当前用户 ，返回订单不存在
            throw new BusinessException(Errors.ORDER_NOT_EXIST);
        }
        return orderModel;
    }

    private OrderModel checkOrderOwner(String orderId, String openId){
        UserModel userModel = buyerService.getByOpenId(openId);
        OrderModel orderModel = orderService.get(orderId);
        if(!orderModel.getUserId().equals(userModel.getId())){
            // 该订单不属于当前用户 ，返回订单不存在
            throw new BusinessException(Errors.ORDER_NOT_EXIST);
        }
        return orderModel;
    }

    private OrderModel convertOrderModelFromOrderCreateBean(OrderCreateBean bean){
        OrderModel orderModel = new OrderModel();
        BeanUtils.copyProperties(bean,orderModel);

        List<OrderDetailModel> orderDetailModels = bean.getOrderDetailBeans().stream().map(e -> {
            OrderDetailModel orderDetailModel = new OrderDetailModel();
            BeanUtils.copyProperties(e,orderDetailModel);
            return orderDetailModel;
        }).collect(Collectors.toList());

        orderModel.setOrderDetailModels(orderDetailModels);
        return orderModel;
    }
}
